﻿/*
* CRM_contract.cs
*
* 功 能： N/A
* 类 名： CRM_contract
*
* Ver    变更日期             负责人     变更内容
* ───────────────────────────────────
* V1.0  2015-06-23 18:38:21    黄润伟    
*
* Copyright (c) 2015 www.xhdcrm.com   All rights reserved.
*┌──────────────────────────────────┐
*│　版权所有：黄润伟                      　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/

using System;
using System.Data;
using System.Web;
using XHD.Common;
using XHD.Controller;

namespace XHD.Server
{
    public class CRM_contract
    {
        public static BLL.CRM_contract contract = new BLL.CRM_contract();
        public static Model.CRM_contract model = new Model.CRM_contract();

        public HttpContext Context;
        public int emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;


        public CRM_contract()
        {
        }

        public CRM_contract(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.ID;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
        }

        public void save()
        {
            model.Serialnumber = PageValidate.InputText(request["T_contract_num"], 255);
            model.Contract_name = PageValidate.InputText(request["T_contract_name"], 255);
            model.Customer_id = int.Parse(request["T_Customer_val"]);

            model.C_depid = int.Parse(request["c_dep_val"]);
            model.C_empid = int.Parse(request["c_emp_val"]);

            model.Contract_amount = decimal.Parse(request["T_contract_amount"]);
            model.Pay_cycle = int.Parse(request["T_pay_cycle"]);

            model.Start_date = PageValidate.InputText(request["T_start_date"], 255);
            model.End_date = PageValidate.InputText(request["T_end_date"], 255);
            model.Sign_date = PageValidate.InputText(request["T_contract_date"], 255);
            model.Customer_Contractor = PageValidate.InputText(request["T_contractor"], 255);
            model.Our_Contractor_depid = int.Parse(request["f_dep_val"]);
            model.Our_Contractor_id = int.Parse(request["f_emp_val"]);

            model.Main_Content = PageValidate.InputText(request["T_content"], int.MaxValue);
            model.Remarks = PageValidate.InputText(request["T_remarks"], int.MaxValue);

            string cid = PageValidate.InputText(request["cid"], 50);
            int contract_id = -1;
            if (PageValidate.IsNumber(cid))
            {
                contract_id = int.Parse(cid);
                model.id = contract_id;

                DataSet ds = contract.GetList(string.Format(" id = {0}", contract_id));
                DataRow dr = ds.Tables[0].Rows[0];

                contract.Update(model);

                var log = new sys_log();
                int UserID = emp_id;
                string UserName = emp_name;
                string IPStreet = request.UserHostAddress;
                string EventTitle = model.Contract_name;
                string EventType = "合同修改";
                int EventID = model.id;
                string Log_Content = null;

                if (dr["Customer_name"].ToString() != request["T_Customer"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "客户", dr["Customer_name"], request["T_Customer"]);

                if (dr["Contract_name"].ToString() != request["T_contract_name"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "合同名称", dr["Contract_name"],
                        request["T_contract_name"]);

                if (dr["Serialnumber"].ToString() != request["T_contract_num"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "合同编号", dr["Serialnumber"],
                        request["T_contract_num"]);

                if (dr["Contract_amount"].ToString() != request["T_contract_amount"].Replace(",", "").Replace(".00", ""))
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "合同金额", dr["Contract_amount"],
                        request["T_contract_amount"].Replace(",", "").Replace(".00", ""));

                if (dr["Customer_Contractor"].ToString() != request["T_contractor"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "对方签约人", dr["Customer_Contractor"],
                        request["T_contractor"]);

                if (dr["Our_Contractor_depname"].ToString() != request["f_dep"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "我方签约人部门", dr["Our_Contractor_depname"],
                        request["f_dep"]);

                if (dr["Our_Contractor_name"].ToString() != request["f_emp"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "我方签约人名字", dr["Our_Contractor_name"],
                        request["f_emp"]);

                if (dr["Main_Content"].ToString() != request["T_content"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "主要条款", "原内容被修改", "原内容被修改");

                if (dr["Remarks"].ToString() != request["T_remarks"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "备注", dr["Remarks"], request["T_remarks"]);

                if (dr["Start_date"].ToString() != request["T_start_date"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "开始时间", dr["Start_date"], request["T_start_date"]);

                if (dr["End_date"].ToString() != request["T_end_date"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "结束时间", dr["End_date"], request["T_end_date"]);

                if (dr["Sign_date"].ToString() != request["T_contract_date"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "签约时间", dr["Sign_date"], request["T_contract_date"]);

                if (!string.IsNullOrEmpty(Log_Content))
                    log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, Log_Content);
            }
            else
            {
                model.isDelete = 0;
                model.Creater_id = emp_id;
                model.Creater_name = emp_name;
                model.Create_time = DateTime.Now;

                contract_id = contract.Add(model);
            }

            //attachment
            var cca = new BLL.CRM_contract_attachment();
            string page_id = PageValidate.InputText(request["page_id"], 255);
            cca.UpdateMailid(contract_id, page_id);
        }

        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " id";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = "desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = "1=1";

            string customer_id = request["cid"];
            if (PageValidate.IsNumber((customer_id)))
                serchtxt += $" and Customer_id={ int.Parse(customer_id)}";

            if (!string.IsNullOrEmpty(request["company"]))
                serchtxt += $" and Customer_id in (select id from CRM_Customer where Customer like N'%{ PageValidate.InputText(request["company"], 255)}%')";

            if (!string.IsNullOrEmpty(request["contact"]))
                serchtxt += $" and Contract_name like N'%{ PageValidate.InputText(request["contact"], 255) }%'";

            if (!string.IsNullOrEmpty(request["department"]))
                serchtxt += $" and C_depid ={ int.Parse(request["department_val"])}";

            if (!string.IsNullOrEmpty(request["employee"]))
                serchtxt += $" and C_empid ={ int.Parse(request["employee_val"])}";

            if (!string.IsNullOrEmpty(request["signdate1"]))
                serchtxt += $" and Sign_date >= '{ PageValidate.InputText(request["signdate1"], 255) }'";

            if (!string.IsNullOrEmpty(request["signdate2"]))
            {
                DateTime enddate = DateTime.Parse(request["signdate2"]).AddHours(23).AddMinutes(59).AddSeconds(59);
                serchtxt += $" and Sign_date  <= '{ enddate }'";
            }
            if (!string.IsNullOrEmpty(request["startdate1"]))
                serchtxt += $" and Start_date >= '{ PageValidate.InputText(request["startdate1"], 255) }'";

            if (!string.IsNullOrEmpty(request["startdate2"]))
            {
                DateTime enddate = DateTime.Parse(request["startdate2"]).AddHours(23).AddMinutes(59).AddSeconds(59);
                serchtxt += $" and Start_date  <= '{ enddate }'";
            }
            if (!string.IsNullOrEmpty(request["enddate1"]))
                serchtxt += $" and End_date >= '{ PageValidate.InputText(request["enddate1"], 255) }'";

            if (!string.IsNullOrEmpty(request["enddate2"]))
            {
                DateTime enddate = DateTime.Parse(request["enddate2"]).AddHours(23).AddMinutes(59).AddSeconds(59);
                serchtxt += $" and End_date  <= '{ enddate }'";
            }

            //权限 
            serchtxt += DataAuth();

            DataSet ds = contract.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

            return GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
        }

        public string form(int id)
        {
            DataSet ds = contract.GetList(string.Format(" id = {0} " + DataAuth(), id));
            string dt = DataToJson.DataToJSON(ds);
            return dt;
        }

        //del
        public string del(int id)
        {
            DataSet ds = contract.GetList($"id = {id}");

            bool canedel = true;
            if (uid != "admin")
            {
                var dataauth = new GetDataAuth();
                string txt = dataauth.GetDataAuthByid("4", "Sys_del", emp_id);

                string[] arr = txt.Split(':');
                switch (arr[0])
                {
                    case "none":
                        canedel = false;
                        break;
                    case "my":
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i]["C_empid"].ToString() == arr[1])
                                canedel = true;
                            else
                                canedel = false;
                        }
                        break;
                    case "dep":
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i]["C_depid"].ToString() == arr[1])
                                canedel = true;
                            else
                                canedel = false;
                        }
                        break;
                    case "all":
                        canedel = true;
                        break;
                }
            }
            if (canedel)
            {
                bool isdel = contract.Delete(id);
                var atta = new BLL.CRM_contract_attachment();
                atta.Delete($"contract_id = {id}");
                if (isdel)
                {
                    //日志
                    string EventType = "合同删除";

                    int UserID = emp_id;
                    string UserName = emp_name;
                    string IPStreet = request.UserHostAddress;
                    int EventID = id;
                    string EventTitle = ds.Tables[0].Rows[0]["Contract_name"].ToString();

                    var log = new sys_log();

                    log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null);

                    return "true";
                }
                return "false";
            }
            return "false";
        }

        public string Compared_empcuscontract()
        {
            string idlist = PageValidate.InputText(request["idlist"], int.MaxValue);
            string year1 = PageValidate.InputText(request["year1"], 50);
            string year2 = PageValidate.InputText(request["year2"], 50);
            string month1 = PageValidate.InputText(request["month1"], 50);
            string month2 = PageValidate.InputText(request["month2"], 50);

            if (idlist.Length < 1)
                idlist = "0";

            string[] pid = idlist.Split(';');
            string pidlist = "";
            for (int i = 0; i < pid.Length; i++)
            {
                int j = pid[i].IndexOf('p');
                if (j != -1)
                {
                    pidlist += pid[i].Replace("p", "") + ",";
                }
            }
            pidlist += "0";

            var post = new BLL.hr_post();
            DataSet dspost = post.GetList("id in(" + pidlist + ")");

            string emplist = "(";

            for (int i = 0; i < dspost.Tables[0].Rows.Count; i++)
            {
                emplist += dspost.Tables[0].Rows[i]["emp_id"] + ",";
            }
            emplist += "0)";

            //context.Response.Write(emplist);

            DataSet ds = contract.Compared_empcuscontract(year1, month1, year2, month2, emplist);

            string dt = GetGridJSON.DataTableToJSON(ds.Tables[0]);
            return dt;
        }

        public string emp_cuscontract()
        {
            string idlist = PageValidate.InputText(request["idlist"], int.MaxValue);
            string syear = request["syear"];

            if (idlist.Length < 1)
                idlist = "0";

            string[] pid = idlist.Split(';');
            string pidlist = "";
            for (int i = 0; i < pid.Length; i++)
            {
                int j = pid[i].IndexOf('p');
                if (j != -1)
                {
                    pidlist += pid[i].Replace("p", "") + ",";
                }
            }
            pidlist += "0";

            var post = new BLL.hr_post();
            DataSet dspost = post.GetList("id in(" + pidlist + ")");

            string emplist = "(";

            for (int i = 0; i < dspost.Tables[0].Rows.Count; i++)
            {
                emplist += dspost.Tables[0].Rows[i]["emp_id"] + ",";
            }
            emplist += "0)";
            //context.Response.Write(emplist);

            DataSet ds = contract.report_empcontract(int.Parse(syear), emplist);

            string dt = GetGridJSON.DataTableToJSON(ds.Tables[0]);
            return dt;
        }

        private string DataAuth()
        {
            //权限            
            string uid = employee.uid;
            string returntxt = " ";

            if (uid != "admin")
            {
                {
                    var dataauth = new GetDataAuth();
                    string txt = dataauth.GetDataAuthByid("4", "Sys_view", emp_id);

                    string[] arr = txt.Split(':');
                    switch (arr[0])
                    {
                        case "none":
                            returntxt = " and 1=2 ";
                            break;
                        case "my":
                            returntxt = " and  C_empid=" + arr[1];
                            break;
                        case "dep":
                            if (string.IsNullOrEmpty(arr[1]))
                                returntxt = " and  C_empid=" + int.Parse(uid);
                            else
                                returntxt = " and  C_depid=" + arr[1];
                            break;
                        case "depall":
                            var dep = new BLL.hr_department();
                            DataSet ds = dep.GetAllList();
                            string deptask = GetTasks.GetDepTask(int.Parse(arr[1]), ds.Tables[0]);
                            string intext = arr[1] + "," + deptask;
                            returntxt = " and  C_depid in (" + intext.TrimEnd(',') + ")";
                            break;
                    }
                }
            }
            return returntxt;
        }
    }
}